package com.icarsaas.saas.master.utils;

import com.icarsaas.saas.master.model.MasterTenant;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;

/**
 * 数据库DataSource工具类
 * 
 * @author chlingm
 *
 */
public final class DataSourceUtil {

    private static final Logger LOG = LoggerFactory
            .getLogger(DataSourceUtil.class);

    /**
     * 配置并创建每个租户的datasource
     * 
     * @param masterTenant
     * @return
     */
    public static DataSource createAndConfigureDataSource(MasterTenant masterTenant) {
        HikariDataSource ds = new HikariDataSource();
        ds.setUsername(masterTenant.getUsername());
        ds.setPassword(masterTenant.getPassword());
        ds.setJdbcUrl(masterTenant.getUrl());
        ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        // HikariCP settings
        // 数据库连接超时时间,默认30S
        ds.setConnectionTimeout(masterTenant.getConnectionTimeout());//20000
        // 最小空闲连接数量
        ds.setMinimumIdle(masterTenant.getMinimumIdle());// 10
        // 最大连接数量
        ds.setMaximumPoolSize(masterTenant.getMaximumPoolSize());//20
        // 空闲连接存活最大时间,默认600000S
        ds.setIdleTimeout(masterTenant.getIdleTimeout());//300000
        // Setting up a pool name for each tenant datasource
        String tenantId = masterTenant.getTenantId();
        String tenantConnectionPoolName = tenantId + "-connection-pool";
        ds.setPoolName(tenantConnectionPoolName);
        LOG.info("Configured datasource:" + masterTenant.getTenantId() + ". Connection poolname:" + tenantConnectionPoolName);
        return ds;
    }
}
